package cn.datawin.cmppclient.sender.service;

import cn.datawin.cmppclient.sender.entity.Provider;
import cn.datawin.cmppclient.sender.entity.SubmitStatus;
import cn.datawin.cmppclient.sender.handler.CmppMessageResponseHandler;
import cn.datawin.cmppclient.sender.util.CodeUtil;
import cn.datawin.cmppclient.sender.util.SMSUtil;
import cn.datawin.sms.cmpp2.SmsDetailLog;
import com.drondea.sms.channel.ChannelSession;
import com.drondea.sms.common.SequenceNumber;
import com.drondea.sms.message.IMessage;
import com.drondea.sms.message.cmpp.CmppSubmitRequestMessage;
import com.drondea.sms.message.cmpp.CmppSubmitResponseMessage;
import com.drondea.sms.thirdparty.SmsDcs;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.Date;

@Service("cmppService")
public class CmppService {


	protected String getRequestContent(Provider provider, String content, String signature, int pkNumber, int pkTotal) {
		if (StringUtils.isEmpty(signature)) {
			return content;
		}
//        //客户端签名不用处理
//        if (StringUtils.defaultIfEmpty(channel.getSignature_Direction_Code(), SignatureType.CUSTOMIZE.toString())
//                .equalsIgnoreCase(SignatureType.CUSTOMIZE.toString())) {
//            return content;
//        }
//
//        //前置签名第一个内容要拼接上签名
//        if (pkNumber == 1 && StringUtils.defaultIfEmpty(channel.getSignature_Position(), SignaturePosition.PREFIX.toString())
//                .equalsIgnoreCase(SignaturePosition.PREFIX.toString()) && !content.startsWith(signature)) {
//            content = signature + content;
//        }
//
//        //后置签名最后一个内容要拼接上签名
//        if (pkNumber == pkTotal && StringUtils.defaultIfEmpty(channel.getSignature_Position(), SignaturePosition.PREFIX.toString())
//                .equalsIgnoreCase(SignaturePosition.SUFFIX.toString())) {
//            content = content + signature;
//        }
		return content;
	}

	public String getSubmitContent(SmsDetailLog smsDetailLog, Provider provider) {
		String content = smsDetailLog.getContent();
		//签名位置根据通道配置置换
//        if (StringUtils.defaultIfEmpty(channel.getSignature_Position(), SignaturePosition.PREFIX.toString())
//                .equalsIgnoreCase(SignaturePosition.PREFIX.toString())) {
//            content = SMSUtil.resetSignaturePosition(content, submit.getSignature(), SignaturePosition.PREFIX);
//        } else {
//            content = SMSUtil.resetSignaturePosition(content, submit.getSignature(), SignaturePosition.SUFFIX);
//        }
		return content;
	}

	public IMessage getSubmitMessage(Provider provider, SmsDetailLog smsDetailLog, ChannelSession channelSession) {
		smsDetailLog.setChannelMsgId(CodeUtil.buildMsgNo());
		// 这两个时间是初始时间，提交时间和创建时间会被重置
		smsDetailLog.setSubmitDate(new Date());

		// 通道的group_code
//        submit.setGroupCode(provider.getGroup_Code());

		InetSocketAddress socketAddress = (InetSocketAddress) channelSession.getChannel().localAddress();
		smsDetailLog.setSenderLocalPort(String.valueOf(socketAddress.getPort()));

		IMessage requestMessage = wrapSubmitRequest(channelSession, provider, smsDetailLog);

//        String enterpriseMsgId = submit.getEnterpriseMsgId();
//        String[] msgIds = null;
//        if (StringUtils.isNotEmpty(enterpriseMsgId)) {
//            msgIds = enterpriseMsgId.split(",");
//        }
//
//        String[] finalMsgIds = msgIds;
		requestMessage.setMessageResponseHandler(new CmppMessageResponseHandler(smsDetailLog));
		return requestMessage;
	}

    protected void setRequestInfo(Provider channel, SmsDetailLog smsDetailLog, IMessage request) {
        CmppSubmitRequestMessage requestMessage = (CmppSubmitRequestMessage) request;
        smsDetailLog.setSequence((int) requestMessage.getPkNumber());
        smsDetailLog.setContent(requestMessage.getMsgContent());
        smsDetailLog.setContentLength(smsDetailLog.getContent().length());

        String content = requestMessage.getMsgContent();
        //修正运营侧去掉内容签名的问题
        content = getRequestContent(channel, content, smsDetailLog.getSignature(), requestMessage.getPkNumber(), requestMessage.getPkTotal());
        //这里的request是拿到的每个片段的内容
        smsDetailLog.setContent(content);
        smsDetailLog.setContentLength(smsDetailLog.getContent().length());
        smsDetailLog.setSPNumber(requestMessage.getSrcId());
    }


    public SubmitStatus parseSubmitResponse(IMessage response, SmsDetailLog smsDetailLog) {
        CmppSubmitResponseMessage srp = (CmppSubmitResponseMessage) response;
        smsDetailLog.setSubmitDescription(String.valueOf(srp.getResult()));
        //上游返回的msgId,唯一标识一个消息
        smsDetailLog.setChannelMsgId(srp.getMsgId().toString());
        if (0 == srp.getResult()) {
            return SubmitStatus.SUCCESS;
        }
        return SubmitStatus.FAILD;
    }

    protected IMessage wrapSubmitRequest(ChannelSession channelSession, Provider provider, SmsDetailLog smsDetailLog) {
        //拼接通道的码号
        String srcId = SMSUtil.getSpNumber(provider, smsDetailLog.getSubCode());
        CmppSubmitRequestMessage requestMessage = new CmppSubmitRequestMessage();
        SequenceNumber sequenceNumber = channelSession.getSequenceNumber();
        requestMessage.getHeader().setSequenceId(sequenceNumber.next());
        String content = getSubmitContent(smsDetailLog, provider);
//        requestMessage.setSignature(submit.getSignature());

//        String protocolType = submit.getProtocolTypeCode();
        // TODO: 2022/11/29
        if (StringUtils.isEmpty(smsDetailLog.getCharset())) {
            requestMessage.setMsgContent(content);
            //设置编码
            smsDetailLog.setCharset(SMSUtil.getCharsetByByte(requestMessage.getMsgFmt().getValue()));
        } else {
            requestMessage.setMsgContent(content, new SmsDcs(SMSUtil.getGeneralDataCodingDcs(smsDetailLog.getCharset())));
        }

        String phoneNo = smsDetailLog.getPhoneNos();
        requestMessage.setDestUsrTl((short) 1);
        requestMessage.setDestTerminalId(new String[]{phoneNo});
        requestMessage.setSrcId(srcId);
//		requestMessage.setServiceId(ChannelUtil.getParameterValue(otherParameters, "service_id", "0000000000"));
//		requestMessage.setFeeUserType(ChannelUtil.getParameterShortValue(otherParameters, "fee_user_type", (short) 2));
//		requestMessage.setFeeTerminalId(ChannelUtil.getParameterValue(otherParameters, "fee_terminal_id", ""));
//		requestMessage.setMsgSrc(ChannelUtil.getParameterValue(otherParameters, "msg_src", ""));
//		requestMessage.setRegisteredDelivery(
//				ChannelUtil.getParameterShortValue(otherParameters, "registered_delivery", (short) 1));
        // TODO: 2022/11/29
        requestMessage.setServiceId("0000000000");
        requestMessage.setFeeUserType((short) 2);
        requestMessage.setFeeTerminalId("");
        requestMessage.setMsgSrc(provider.getAccount());
        requestMessage.setRegisteredDelivery((short) 1);

        return requestMessage;
    }
}
